<template>
	<!--size抽屉宽度（或高度）  default 378px 和 large 736px -->
	<a-drawer v-model:open="visible" ref="employeeDetailModalRef" class="edit-drawer modal-fixed-bottom"
		root-class-name="root-customer-drawer" width="800px" :closable="false" @close="onClose">
		<div class="closeable" @click="onClose">{{ $t('self.closeButton') }}</div>
		<div class="modal-header">{{ title }}</div>
		<a-form :model="formState" :rules="formRules" :label-col="labelCol" :wrapper-col="wrapperCol"
			@finish="onSubmit">
			<a-form-item :label="$t('self.businessCharging.tips1')" name="pileName">
				<a-input allow-clear v-model:value="formState.pileName" placeholder="" />
			</a-form-item>

			<a-form-item :label="$t('self.businessCharging.tips26')" name="pileSer">
				<a-input allow-clear v-model:value="formState.pileSeri" placeholder="" />
			</a-form-item>

			<!--  -->
			<a-form-item name="authorizedCountry" :label="$t('self.operators.tips46')" >
				<a-select allow-clear v-model:value="formState.authorizedCountry" 
				:options="africaCountryOptions"   :field-names="{ label: 'display', value: 'value' }"  @change="handleAfricaCountryChange"
				:placeholder="$t('self.pleaseChoose')">
				</a-select>
			</a-form-item>
			<a-form-item name="authorizedCity" :label="$t('self.operators.tips45')">
				<a-select allow-clear v-model:value="formState.authorizedCity" 
				:options="africaTestTypeOptions"
				:field-names="{ label: 'label', value: 'value' }" @change="handleAfricaTestTypeChange"
				:placeholder="$t('self.pleaseChoose')">
				</a-select>
			</a-form-item>




			<a-form-item :label="$t('self.businessCharging.tips7')" name="pileType">
				<a-select v-model:value="formState.pileType" :options="[
            { label: $t('self.businessCharging.types.tips1'), value: 1 },
            { label: $t('self.businessCharging.types.tips2'), value: 2 },
        ]" :placeholder="$t('self.pleaseChoose')" />
			</a-form-item>
			<a-form-item :label="$t('self.businessCharging.tips8')" name="chargePilePowerLow">
				<a-input allow-clear v-model:value="formState.chargePilePowerLow" placeholder="" />
			</a-form-item>
			<a-form-item :label="$t('self.businessCharging.tips9')" name="chargePilePowerMax">
				<a-input allow-clear v-model:value="formState.chargePilePowerMax" placeholder="" />
			</a-form-item>

			<!--前置服务-->
			<a-form-item :label="$t('self.businessCharging.tips14')" name="appNode">
				<a-select v-model:value="formState.appNode" :options="qzfwOptions"
					:fieldNames="{label: 'label',value: 'key'}" :placeholder="$t('self.pleaseChoose')" />
			</a-form-item>

			<!--  -->
			<a-form-item :label="$t('self.businessStation.tips18')" name="chargeColor">
				<a-input allow-clear v-model:value="formState.chargeColor" placeholder="" />
			</a-form-item>



			<a-form-item :label="$t('self.businessCharging.tips15')" name="gunNum">
				<a-input-number allow-clear v-model:value="formState.gunNum" style="width: 100%" />
			</a-form-item>
			<!--充电接口-->
			<a-form-item :label="$t('self.businessCharging.tips16')" name="chargeInterface">
				<a-select mode="multiple" v-model:value="formState.chargeInterface" :options="cdqjkOptions"
					:fieldNames="{label: 'label',value: 'key'}" :placeholder="$t('self.pleaseChoose')" />
			</a-form-item>
			<a-form-item :label="$t('self.businessCharging.tips17')" name="pileNo" v-if="mode === 'add'">
				<a-input-number allow-clear v-model:value="formState.pileNo" style="width: 100%" />
			</a-form-item>

			<a-form-item :label="$t('self.businessStation.tips19')" name="SuperAdminPassword">
				<a-input allow-clear v-model:value="formState.SuperAdminPassword" placeholder="" />
			</a-form-item>
			<a-form-item :label="$t('self.businessStation.tips20')" name="GeneratlPassword'">
				<a-input allow-clear v-model:value="formState.GeneratlPassword" placeholder="" />
			</a-form-item>
			<a-form-item :label="$t('self.businessStation.tips21')" name="TechCrewPassword">
				<a-input allow-clear v-model:value="formState.TechCrewPassword" placeholder="" />
			</a-form-item>			
			<a-form-item :label="$t('self.businessStation.tips22')" name="Password1">
				<a-input allow-clear v-model:value="formState.Password1" placeholder="" />
			</a-form-item>
			<a-form-item :label="$t('self.businessStation.tips23')" name="Password2">
				<a-input allow-clear v-model:value="formState.Password2" placeholder="" />
			</a-form-item>
			<a-form-item :label="$t('self.businessStation.tips24')" name="Password3">
				<a-input allow-clear v-model:value="formState.Password3" placeholder="" />
			</a-form-item>	
			<a-form-item :label="$t('self.businessStation.tips25')" name="Password4">
				<a-input allow-clear v-model:value="formState.Password4" placeholder="" />
			</a-form-item>
			<a-form-item :label="$t('self.businessStation.tips26')" name="Password5">
				<a-input allow-clear v-model:value="formState.Password5" placeholder="" />
			</a-form-item>

			<div class="base-flex base-rows base-align-items-center base-justify-content-center footer">
				<a-button type="primary" html-type="submit">{{ $t('self.submitButton') }}</a-button>
				<a-button class="base-ml10" @click="onClose">{{ $t('self.cancelButton') }}</a-button>
			</div>
		</a-form>
	</a-drawer>
</template>

<script setup>
	import {
		computed,
		getCurrentInstance,
		onMounted,
		ref
	} from 'vue'
	import {
		message
	} from 'ant-design-vue'
	import chooseAreaForLocal from '@/components/choose/choose-area-for-local.vue'
	const {
		proxy
	} = getCurrentInstance()
	const $TOOL = proxy.$TOOL
	const $API = proxy.$API
	const $T = proxy.$t
	const emit = defineEmits(['close', 'ok'])

	const visible = ref(false)
	// 模式，add新增，show查看，edit编辑
	const mode = ref('add')
	const labelCol = {
		style: {
			width: '230px',
		},
	};
	const wrapperCol = {
		span: 16,
	};
	const title = ref('')


	import cityData from '@/config/data.js'
	import dayjs from 'dayjs'
	const countryAuthorizeOptions = ref([])
	const cityRaw =  cityData.cityRaw
	const formState = ref({
		"id": '',
		"stationId": "", // 站点id
		"policyId": "", // 资费id
		"pileName": "", // 充电桩名称
		"pileSeri": "", // 桩序列号
		"pileType": null, // 桩类型，直流还是交流
		"chargeInterface": [], // 充电接口，Type 2,SAE J1772 (2个用逗号隔开，我需要改下接口改成字符串)
		"chargePilePowerLow": '', // 功率
		"chargePilePowerMax": '', // 最大功率
		"orgId": "", // 运营商id
		"pileNo": "", // 充电桩总数
		"gunNum": "", // 枪数量，添加桩数量
		"appNode": "1", // 前置服务
		"agreement": 0,
		chargeColor:'',
		authorizedCountry: null,
		authorizedCountryCode: null,
  		authorizedCity: null, // 城市名称
		SuperAdminPassword:'',
		GeneratlPassword:'',
		TechCrewPassword:'',
		Password1:'',
		Password2:'',
		Password3:'',
		Password4:'',
		Password5:'',
		pileSer:''
		// ChargerStatus:'',
	})
	// 桩协议的下拉列表
	const cdzXYOptions = ref([{
		label: 'ocpp1.6J',
		key: 1
	}])
	// 前置服务的下拉列表
	const qzfwOptions = ref([{
		label: 'note1',
		key: '1'
	}])
	// 充电接口的下拉列表
	const cdqjkOptions = ref([{
			label: 'Type 2',
			key: 'Type 2'
		},
		{
			label: 'SAE J1772',
			key: 'SAE J1772'
		},
		{
			label: 'CHAdeMO',
			key: 'CHAdeMO'
		},
		{
			label: 'GB/T',
			key: 'GB/T'
		},
		{
			label: 'Tesla',
			key: 'Tesla'
		}
	])

	// const ChargerStatusOptions = ref([{
	// 		label: $T('self.businessStation.vehicleType.tips1'),
	// 		value: 0
	// 	},
	// 	{
	// 		label: $T('self.businessStation.vehicleType.tips2'),
	// 		value: 1
	// 	},
	// 	{
	// 		label: $T('self.businessStation.vehicleType.tips3'),
	// 		value: 2
	// 	},
	// 	{
	// 		label: $T('self.businessStation.vehicleType.tips4'),
	// 		value: 3
	// 	},
	// ])
	const vehicleOptions = ref([{
			label: $T('self.businessStation.vehicleType.tips1'),
			value: 0
		},
		{
			label: $T('self.businessStation.vehicleType.tips2'),
			value: 1
		},
		{
			label: $T('self.businessStation.vehicleType.tips3'),
			value: 2
		},
		{
			label: $T('self.businessStation.vehicleType.tips4'),
			value: 3
		},
	])
	const formRules = ref({
		pileName: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessCharging.tips1'),
			trigger: 'change'
		}],
		pileSeri: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessCharging.tips1'),
			trigger: 'change'
		}],
		pileType: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessCharging.tips3'),
			trigger: 'change'
		}],
		chargePilePowerLow: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessCharging.tips8'),
			trigger: 'change'
		}],
		chargePilePowerMax: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessCharging.tips9'),
			trigger: 'change'
		}],
		appNode: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessCharging.tips14'),
			trigger: 'change'
		}],
		gunNum: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessCharging.tips15'),
			trigger: 'change'
		}],
		chargeInterface: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessCharging.tips16'),
			trigger: 'change'
		}],
		agreement: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessCharging.modal.col14'),
			trigger: 'change'
		}],
		chargeColor: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessCharging.tips16'),
			trigger: 'change'
		}],
		appNode: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessCharging.modal.col14'),
			trigger: 'change'
		}],

		SuperAdminPassword: [{
			required: true,
			message: $T('self.pleaseInput'),
			trigger: 'change'
		}],
		GeneratlPassword: [{
			required: true,
			message: $T('self.pleaseInput'),
			trigger: 'change'
		}],
		TechCrewPassword: [{
			required: true,
			message: $T('self.pleaseInput'),
			trigger: 'change'
		}],
		Password1: [{
			required: true,
			message: $T('self.pleaseInput'),
			trigger: 'change'
		}],
		Password2: [{
			required: true,
			message: $T('self.pleaseInput'),
			trigger: 'change'
		}],
		Password3: [{
			required: true,
			message: $T('self.pleaseInput'),
			trigger: 'change'
		}],
		Password4: [{
			required: true,
			message: $T('self.pleaseInput'),
			trigger: 'change'
		}],
		Password5: [{
			required: true,
			message: $T('self.pleaseInput'),
			trigger: 'change'
		}],

		

		authorizedCountry: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col7'),trigger: 'change'}],
  		authorizedCity: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col7'),trigger: 'change'}],
	})

	onMounted(async () => {

	})

	const onSubmit = (values) => {
		const params = {
			...formState.value
		}
		params.chargeInterface = params.chargeInterface.join(',')

		// console.log("=======================",params)
		// return
		if (mode.value === 'add') {
			// 添加
			$API.backend.businessCharging.add.post(params).then(res => {
				message.success($T('self.message.success'))
				onReset()
				visible.value = false
				emit('ok')
			}).catch(err => {
				message.error(err.msg);
			})
		} else {
			// 修改
			$API.backend.businessCharging.edit.post(params).then(res => {
				message.success($T('self.message.success'))
				onReset()
				visible.value = false
				emit('ok')
			}).catch(err => {
				message.error(err.msg);
			})
		}
		// console.log(formState.value)
		// console.log('submit!', values);
	}

	const africaTestTypeOptions = computed(() => {
		const selectedCountry = formState.value.authorizedCountryCode;
		if (!selectedCountry) return []; 

		const cities = cityRaw[selectedCountry] || [];
		return cities.map(c => ({
			label: `${c.labelCn} / ${c.labelEn}` + (c.labelRW ? ` / ${c.labelRW}` : ''),
			value: `${selectedCountry}_${c.labelEn}`, 
			countryCode: selectedCountry,
			labelCn: c.labelCn,
			labelEn: c.labelEn,
			labelRW: c.labelRW
		}));
	});
	const handleAfricaCountryChange = async (countryCode) => {
		formState.value.authorizedCountryCode = countryCode;
		// formState.value.authorizedCity = null;
		const selectedCountry = africaCountryOptions.find(item => item.value === countryCode);
		console.log('selectedCountry', selectedCountry)
		formState.value.authorizedCountry = selectedCountry ? selectedCountry.labelEn : null;
	};
	const africaCountryOptions = cityData.africaCountryOptions.map(item => ({
		...item,
		display: `${item.labelCn} / ${item.labelEn}` + (item.labelRW ? ` / ${item.labelRW}` : '')
	}));
	const handleAfricaTestTypeChange = (testType) => {
		// formState.value.africaTestType = testType;
		const selectedCity = africaTestTypeOptions.value.find(item => item.value === testType);
		console.log('selectedCity', selectedCity)
		formState.value.authorizedCity = selectedCity ? selectedCity.labelEn : null;
	};
	const onReset = () => {
		formState.value = {
			"id": '',
			"stationId": "", // 站点id
			"policyId": "", // 资费id
			"pileName": "", // 充电桩名称
			"pileSeri": "", // 桩序列号
			"pileType": null, // 桩类型，直流还是交流
			"chargeInterface": [], // 充电接口，Type 2,SAE J1772 (2个用逗号隔开，我需要改下接口改成字符串)
			"chargePilePowerLow": '', // 功率
			"chargePilePowerMax": '', // 最大功率
			"orgId": "", // 运营商id
			"pileNo": "", // 充电桩总数
			"gunNum": "", // 枪数量，添加桩数量
			"agreement": 0, // 桩协议
			"appNode": "1",
			chargeColor:'',
			authorizedCountry: [],
  			authorizedCity: null,
			GeneratlPassword:'',
			TechCrewPassword:'',
			Password1:'',
			Password2:'',
			Password3:'',
			Password4:'',
			Password5:'',
			// ChargerStatus:''
		}
	}

	const onClose = () => {
		onReset()
		visible.value = false
		emit('close')
	}

	const add = (stationId) => {
		mode.value = 'add'
		title.value = $T('self.businessCharging.tips19')
		formState.value.stationId = stationId
		visible.value = true
	}
	const edit = (record) => {
		console.log("---------------------",record)
		mode.value = 'edit'
		const params = {
			...record
		}
		// console.log('params', params)
		params.chargeInterface = params.chargeInterface ? params.chargeInterface.split(",") : []
		// console.log('vehicleOptions', vehicleOptions.value) 
		formState.value.SuperAdminPassword = record.superAdminPassword || '';
		formState.value.GeneratlPassword = record.generatlPassword || '';
		formState.value.TechCrewPassword = record.techCrewPassword || '';
		formState.value.Password1 = record.password1 || '';
		formState.value.Password2 = record.password2 || '';
		formState.value.Password3 = record.password3 || '';
		formState.value.Password4 = record.password4 || '';
		formState.value.Password5 = record.password5 || '';
		formState.value.chargeColor = record.chargerColor || '';
		// const agreementOption = vehicleOptions.value.find(option => option.value === parseInt(record.agreement, 10))
		// params.agreement = agreementOption.label ? agreementOption.label : vehicleOptions.value[0].label
		$TOOL.array.cloneExistKey(formState.value, params)
		title.value = $T('self.businessCharging.tips20')
		visible.value = true
	}

	// 子组件中要通过defineExpose将方法暴露给父组件
	defineExpose({
		add,
		edit,
	})
</script>

<style lang="scss" scoped>
	.edit-drawer {
		position: relative;

		.closeable {
			@include closeable;
		}
	}
</style>
